﻿using System;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace usbburn
{
    public class SystemMenu
    {
        public const int MF_UNCHECKED = 0x00000000;
        public const int MF_STRING = 0x00000000;
        public const int MF_GRAYED = 0x00000001;
        public const int MF_CHECKED = 0x00000008;
        public const int MF_POPUP = 0x00000010;
        public const int MF_BYPOSITION = 0x00000400;
        public const int MF_BYCOMMAND = 0x00000000;
        public const int MF_SEPARATOR = 0x00000800;

        public const int WM_SYSCOMMAND = 0x0112;

        IntPtr m_handle;

        [DllImport("USER32", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern IntPtr GetSystemMenu(IntPtr WindowHandle, int bReset);

        [DllImport("USER32", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern bool AppendMenu(IntPtr MenuHandle, int Flags, int NewID, String Item);

        [DllImport("USER32", SetLastError = true, CharSet = CharSet.Auto )]
        private static extern bool InsertMenu(IntPtr hMenu, int Position, int Flags, int NewId, String Item);

        public void InsertSeparator(int Pos)
        {
            InsertMenu(Pos, MF_SEPARATOR | MF_BYPOSITION , 0, "");
        }

        public void InsertMenu(int Pos, int ID, String Item)
        {
            InsertMenu(Pos, MF_BYPOSITION | MF_STRING, ID, Item);
        }

        public void InsertMenu(int Pos, int Flags, int ID, String Item)
        {
            if(!InsertMenu(m_handle, Pos, (Int32)Flags, ID, Item))
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
        }

        public void AppendSeparator()
        {
            AppendMenu(0, "", MF_SEPARATOR);
        }

        public void AppendMenu(int ID, String Item)
        {
            AppendMenu(ID, Item, MF_STRING);
        }

        public void AppendMenu(int ID, String Item, int Flags)
        {
            if(!AppendMenu(m_handle, (int)Flags, ID, Item))
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
        }

        public SystemMenu(Form Frm)
        {
            m_handle = GetSystemMenu(Frm.Handle, 0);

            if (m_handle == IntPtr.Zero)
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }
        }

        ~SystemMenu()
        {
            GetSystemMenu(m_handle, 1);
        }
    }
}
